/**
 * index.js
 * 
 * @since 1.0 <2016-3-10> SoChishun <14507247@qq.com> Added.
 */
// 页面变量
window.config = new Function("return {" + $('#window-config-text').text() + "}")();
// 免费字体资源:http://www.fontsquirrel.com 2015-12-4 SoChishun Added.
$(document).ready(function () {
// 布局渲染 2015-12-3 SoChishun Added.
// see:http://layout.jquery-dev.com/index.cfm
    if ('undefined' !== typeof ($.fn.layout)) {
        $('body').layout({
            applyDemoStyles: true,
            spacing_open: 2, //边框的间隙
            spacing_closed: 6, //关闭时边框的间隙
            resizerTip: '可调整大小', //鼠标移到边框时，提示语
            sliderTip: "显示/隐藏面板", //在某个Pane隐藏后，当鼠标移到边框上显示的提示语。
            togglerTip_open: "关闭", //pane打开时，当鼠标移动到边框上按钮上，显示的提示语  
            togglerTip_closed: "打开", //pane关闭时，当鼠标移动到边框上按钮上，显示的提示语  
            togglerLength_open: 150, //pane打开时，边框按钮的长度  
            togglerLength_closed: 300, //pane关闭时，边框按钮的长度,
            // 浏览器改变大小的时候，iframe也跟随缩放 2016-3-10
            onresize: function (name, obj) {
                // 主iframe尺寸自动缩放
                if (name == 'center') {
                    $('main iframe').height(obj.height() - 5);
                }
            },
        }).allowOverflow('north'); // 允许下拉菜单越过框架范围而不出现滚动条
    }
// 导航菜单下拉设置
    if ('undefined' !== typeof ($.fn.superfish)) {
        $('ul.sf-menu').superfish({delay: 100});
    }
    // 侧边栏折叠菜单
    $('.aside-menu').accordion({heightStyle: "content"});
    // 侧边栏菜单自适应高度 
    //$('.aside-menu').height($('.ui-layout-west').height() - $('.aside-clock-zone').height() - $('.aside-user-zone').height() - 10);
    // 日历
    $('.xsui-calendar-panel').datepicker({
        showOtherMonths: true,
        selectOtherMonths: true,
        showWeek: true,
        firstDay: 1,
        changeMonth: true,
        changeYear: true
    });
    // 页面点击事件处理
    click_handler();
// 消息滚动播放插件 2015-12-4 SoChishun Added.
// see:http://www.rjboy.cn/?p=708
    if ('undefined' !== typeof ($.fn.Xslider)) {
        //load_notices(true);
        //setInterval(load_notices, 10000); // 10秒重载一次公告
    }
    // 读取站内信消息数量
    //load_pmcount();
    //setInterval(load_pmcount, 3000); // 3秒重载一次站内信数量
    // 模拟时钟
    moni_clock();
    // 数字时钟
    setInterval(clock, 1000);
});

/**===================================================================================
 * ========================================函数区域====================================
 * ====================================================================================
 */
/**
 * 页面按钮点击事件处理
 * @returns {undefined}
 * @version 1.0 2016-12-27
 */
function click_handler() {
    // 注销登录并退出队列 2016-4-19
    $('.lnk-logout').click(function () {
        if (!confirm('您确定要退出登录吗?')) {
            return false;
        }
        return true;
    })
    // 侧边栏菜单点击事件
    // 点击菜单后，使用iframe打开
    // 点击菜单,保存到访问历史中 2016-3-11
    $('.aside-menu').delegate('li a', 'click', function () {
        load_iframe($(this).attr('href'));
        return false;
    })
    // 点击标题图标返回首页
    $('.logo a').on('click', function () {
        load_iframe($(this).attr('href'));
        return false;
    });
// 编辑对话框 2016-3-10
    $('.xsui-lnk-edit-dialog-g').on('click', function () {
        ifrmDialog.open_edit_dialog($(this));
        return false;
    })
    $('.xsui-lnk-view-dialog-g').on('click', function () {
        ifrmDialog.open_view_dialog($(this));
        return false;
    })
    // 头部菜单鼠标划过事件 2016-11-29
    $('#user-profile, #my-message, #head-clock').mouseover(function () {
        $(this).find('.xsui-dropdown-panel').show();
    }).mouseout(function () {
        $(this).find('.xsui-dropdown-panel').hide();
    });
    // xsui-panel关闭按钮点击事件处理
    $('.xsui-panel-close-button').click(function () {
        $(this).parent().parent().parent().hide();
        return false;
    })

}
/**
 * 获取未读站内信数量
 * <br />使用了Su-Sign内容比对技术.
 * @returns {undefined}
 * @since 1.0 2016-3-12 SoChishun Added.
 */
function load_pmcount() {
    var $dom = $('#pmcount');
    $.get($dom.data('url'), function (data) {
        if (!data || ($dom.data('sign') && $dom.data('sign') == data.sign)) {
            return;
        }
        $dom.text(data.value);
        $dom.data('sign', data.sign);
    })
}

/**
 * 加载公告内容
 * <br />使用了Su-Sign内容比对技术.
 * @param {type} first
 * @returns {undefined}
 * @since VER:1.0; DATE:2016-2-3; AUTHOR:SoChishun; DESC:Added.
 */
function load_notices(first) {
    var $dom = $('#slider-content-list');
    var url = $dom.data('url');
    var href = $dom.data('href');
    if (!url || !href) {
        return;
    }
    if (first) {
        // $dom.html('');
        $dom.empty();
    }
    $.post(url.replace('varsign', $dom.data('sign')), function (data) {
        if (!data || ($dom.data('sign') && $dom.data('sign') == data.sign)) {
            return;
        }
        var str = '';
        for (var i in data.value) {
            str += '<li><a href="' + href.replace('varkey', data.value[i].id) + '" target="_blank" title="' + data.value[i].title + '">' + data.value[i].title + '</a></li>';
        }
        $dom.empty();
        $dom.data('sign', data.sign);
        $dom.html(str);
        if (first) {
            // 初始化公告滚动插件 2016-2-3 SoChishun Added.
            $(".notices-slider").Xslider({
                unitdisplayed: 1,
                numtoMove: 1,
                loop: "cycle",
                dir: "V",
                autoscroll: 2500,
                speed: 300
            });
        }
    })
}

/**
 * 数字时钟
 * @returns {undefined}
 * @since 1.0 <2015-12-4> SoChishun Added.
 * @since VER:1.1; DATE:2016-1-18; AUTHOR:SoChishun; DESC:修正日期错误
 * @example <div id="clock"><span title="">----------------- ---:---:---</span><i class="fa fa-sun-o" title=""></i></div>
 *      setInterval(clock, 1000);
 */
function clock() {
    var d = new Date(); // 测试 new Date(2015,12,4,22,0,0)
    var week = ['天', '一', '二', '三', '四', '五', '六'];
    var odate = {'y': d.getFullYear(), 'm': d.getMonth() + 1, 'd': d.getDate(), 'h': d.getHours(), 'i': d.getMinutes(), 's': d.getSeconds()};
    var sdate = odate.y + '-' + (odate.m < 10 ? '0' + odate.m : odate.m) + '-' + (odate.d < 10 ? '0' + odate.d : odate.d);
    var stime = sdate + ' ' + (odate.h < 10 ? '0' + odate.h : odate.h) + ':' + (odate.i < 10 ? '0' + odate.i : odate.i) + ':<em>' + (odate.s < 10 ? '0' + odate.s : odate.s) + '<em>';
    var sdateinfo = '今天是' + sdate + ', 星期' + week[d.getDay()] + ', 第' + d.getWeekOfYear() + '周';
    var swords = [[2, 5, '早点休息，保重身体!'], [5, 6, '凌晨了，喝口温开水，暖和一下疲惫的心灵'], [8, 12, '一日之计在于晨，加油！'], [12, 13, '享受一顿丰盛的午餐然后，给身体充满能量'], [20, 22, '亲，加班呀，加油!'], [22, 23, '熬夜伤身，请早点休息!']];
    var sword = '';
    var sout = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
    for (var i in swords) {
        if (odate.h >= swords[i][0] && odate.h < swords[i][1]) {
            sword = swords[i][2];
            break;
        }
    }
    $('.xsui-simple-time').text(sout);
    $('.xsui-clear').text(sword);
}
// 模拟时钟 2016-11-30
function moni_clock() {
    day_arr = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    month_arr = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"];
    clockd1_ = {
        "indicate": true,
        "indicate_color": "#222",
        "dial1_color": "#666600",
        "dial2_color": "#81812e",
        "dial3_color": "#9d9d5c",
        "time_add": 1,
        "time_24h": true,
        "date_add": 3,
        "date_add_color": "#999",
    };

    var c = document.getElementById('clock1_');
    cns1_ = c.getContext('2d');
    clock_conti(200, cns1_, clockd1_);
}

// 动态加载iframe 2016-3-10 SoChishun Added.
function load_iframe(ps_url) {
// 销毁iframe，释放iframe所占用的内存(把iframe指向空白页面，这样可以释放大部分内存).
    var iframe = $('main iframe')[0];
    if (iframe) {
        iframe.src = 'about:blank';
        try {
            iframe.contentWindow.document.write('');
            iframe.contentWindow.document.clear();
        } catch (e) {
        }
        iframe.parentNode.removeChild(iframe); // 把iframe从页面移除
    }
// 创建iframe
    var oIfrm = document.createElement("IFRAME");
    oIfrm.src = ps_url;
    oIfrm.scrolling = "no";
    oIfrm.frameBorder = 0;
    oIfrm.width = '100%';
    oIfrm.height = $('.ui-layout-center').height() - 5;
    $("main").append(oIfrm);
    // loading 2016-3-14
    var loading = '<div id="loading" style="position: absolute; left:50%; top:50%; background-color:#FFF; border:solid 1px #CCC; padding:10px; color:#999; z-index: 999">正在加载数据, 请稍后...</div>';
    $('body').append(loading);
    $(oIfrm).load(function () {
        $('body').find('#loading').remove();
    })
}
// 关闭对话框窗口
function close_dialog(name) {
    $('iframe[name="' + name + '"]').attr('src', "about:blank").parent().dialog('close');
}
/**
 * 获取主容器高度
 * @returns Number
 * @since 1.0 2014-8-12 by sutroon
 */
function get_window_height(offset) {
    if (undefined == offset) {
        offset = 0;
    }
    var winHeight = 0;
    if (window.innerHeight) {
        winHeight = window.innerHeight;
    } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
    }
    return winHeight - offset;
}

/**===================================================================================
 * ======================================扩展函数区域==================================
 * ====================================================================================
/**
 * 计算当前日期在本年度的周数
 * @param {Number} weekStart 每周开始于周几：周日：0，周一：1，周二：2 ...，默认为周日
 * @returns {Number}
 * @since 1.0 <2015-12-4> by http://blog.csdn.net/orain/article/details/7063273
 * @example
 (new Date(2015, 11, 4)).getWeekOfYear(); // 当前日期是本年度第几周
 (new Date(2015, 11, 31)).getWeekOfYear(); // 2015 年度有几周(注意：JS 中月的取值范围为 0~11)
 */
Date.prototype.getWeekOfYear = function (weekStart) {
    weekStart = (weekStart || 0) - 0;
    if (isNaN(weekStart) || weekStart > 6)
        weekStart = 0;
    var year = this.getFullYear();
    var firstDay = new Date(year, 0, 1);
    var firstWeekDays = 7 - firstDay.getDay() + weekStart;
    var dayOfYear = (((new Date(year, this.getMonth(), this.getDate())) - firstDay) / (24 * 3600 * 1000)) + 1;
    return Math.ceil((dayOfYear - firstWeekDays) / 7) + 1;
}

/**
 * 计算当前日期在本月份的周数
 * @param {Number} weekStart 每周开始于周几：周日：0，周一：1，周二：2 ...，默认为周日
 * @returns {Number}
 * @since 1.0 <2015-12-4> by http://blog.csdn.net/orain/article/details/7063273
 * @example
 (new Date(2015, 11, 31)).getWeekOfMonth(); // 当前日期是本月第几周(注意：JS 中月的取值范围为 0~11)
 (new Date(2015, 0, 31)).getWeekOfMonth(); // 2015年度1月有几周
 */
Date.prototype.getWeekOfMonth = function (weekStart) {
    weekStart = (weekStart || 0) - 0;
    if (isNaN(weekStart) || weekStart > 6)
        weekStart = 0;
    var dayOfWeek = this.getDay();
    var day = this.getDate();
    return Math.ceil((day - dayOfWeek - 1) / 7) + ((dayOfWeek >= weekStart) ? 1 : 0);
}